﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
using Newtonsoft.Json.Linq;
namespace DmPlayer
{
    public class DmWsClient
    {
        public delegate void OnDmReceived(Dm dm);
        public OnDmReceived onDmReceived;

        public String host { get; private set; }
        public String room { get; private set; }

        private WebSocket ws;

        public DmWsClient(string host, string room)
        {
            this.host = host;
            this.room = room;
        }

        public void connect()
        {
            String url = "ws://" + host + "/live/ws/" + room + "/";

            ws = new WebSocket(url);
            ws.OnMessage += (sender, e) => 
            {
                try
                {
                    JObject dmJson = JObject.Parse(e.Data);
                    if(onDmReceived != null)
                        onDmReceived.Invoke(Dm.FromJson(dmJson));
                }
                catch(Exception ex)
                {
                    //TODO: print log
                }
            };
            ws.OnOpen += (sender, e) => { /*TODO: log*/ };
            ws.OnError += (sender, e) => { /*TODO: log*/ };
            ws.OnClose += (sender, e) => { /*TODO: log*/ };
            ws.Connect();
        }
    }
}
